package top.lywivan.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import top.lywivan.netty.pojo.UserInfo;
import top.lywivan.netty.util.ProtostuffUtil;

import java.util.List;

/**
 * @author :lyw.ivan
 * @date :Created in 2022/8/14
 * @description : 基于ProtoStuff实现解码，将ByteBuff反序列化为UserInfo对象
 * @version: 1.0
 */
public class ProtoStuffDecoder extends MessageToMessageDecoder<ByteBuf> {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        try {
            //获取字节长度
            int length = byteBuf.readableBytes();
            //读取byteBuf中的字节数据
            byte[] bytes=new byte[length];
            byteBuf.readBytes(bytes);
            //反序列化为UserInfo
            UserInfo userInfo = ProtostuffUtil.deserialize(bytes, UserInfo.class);
            list.add(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
